import { useEffect, useMemo, useState } from 'react';
import { Card, Form, Row, Col, Select, Input, Button, Tabs, Table, Empty, Pagination, message } from 'antd';
import { getCopyList, type CopyLogData } from '../../services/login';


export default function CopyLog() {
  const [platform, setPlatform] = useState<string | undefined>(undefined);
  const [itemId, setItemId] = useState<string>('');
  const [title, setTitle] = useState<string>('');
  const [copyState, setCopyState] = useState<string>('-1');
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [data, setData] = useState<CopyLogData[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const columns = useMemo(() => [
    {
      title: '上家商品名称/上家类目',
      dataIndex: 'aliItemTitle',
      key: 'aliItemTitle',
      width: '20%',
      render: (_: unknown, row: CopyLogData) => (
        <div>
          <div>{row.aliItemTitle}</div>
          <div>{row.aliCategory}</div>
        </div>
      ),
    },
    { title: '目标店铺', dataIndex: 'shopName', key: 'shopName', width: '10%' },
    {
      title: '复制状态',
      dataIndex: 'copyState',
      key: 'copyState',
      width: '10%',
      render: (v: number) => {
        const map: Record<number, string> = { 0: '待复制', 1: '复制中', 2: '复制成功', 3: '跳过复制', 4: '停止复制', 5: '取消复制', 6: '复制失败' };
        return map[v] ?? '-';
      },
    },
    {
      title: '创建时间/商品ID',
      dataIndex: 'createTime',
      key: 'createTime',
      width: '25%',
      render: (_: unknown, row: CopyLogData) => (
        <div>
          <div>{row.createTime}</div>
          <div>{row.ecItemId}</div>
        </div>
      ),
    },
  ], []);

  const refresh = async () => {
    try {
      setLoading(true);
      const params = {
        platform,
        tagName: copyState === '-1' ? '全部' : 
                 copyState === '0' ? '待复制' :
                 copyState === '1' ? '复制中' :
                 copyState === '2' ? '复制成功' :
                 copyState === '3' ? '跳过复制' :
                 copyState === '4' ? '停止复制' :
                 copyState === '5' ? '取消复制' :
                 copyState === '6' ? '复制失败' : '全部',
        itemId: itemId || undefined,
        title: title || undefined,
        pageNum,
        pageSize,
      };

      const response = await getCopyList(params);
      console.log('getCopyList 响应:', response);
      const { data: listData, code } = response.result.body;
      
      if (code === 200 && Array.isArray(listData)) {
        setData(listData);
        setTotal(listData.length); // 注意：这里需要根据实际API返回的总数调整
      } else {
        message.error('获取复制记录失败');
        setData([]);
        setTotal(0);
      }
    } catch (error) {
      console.error('获取复制记录失败:', error);
      message.error('获取复制记录失败');
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    refresh();
  }, [platform, itemId, title, copyState, pageNum, pageSize]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div className="copy-log-page">
      <Card style={{ marginBottom: 8 }}>
        <Form layout="vertical">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="铺货平台">
                <Select allowClear placeholder="默认查询全部" value={platform} onChange={setPlatform}
                  options={[{ label: '快手', value: 'kuaishou' }, { label: '抖音', value: 'douyin' }]} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="商品ID">
                <Input placeholder="请输入商品ID" value={itemId} onChange={(e) => setItemId(e.target.value)} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="商品标题">
                <Input placeholder="请输入商品标题" value={title} onChange={(e) => setTitle(e.target.value)} />
              </Form.Item>
            </Col>
            <Col span={6} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <Form.Item>
                <Button type="primary" onClick={refresh}>查询</Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card>
        <Tabs activeKey={copyState} onChange={setCopyState}
          items={[
            { key: '-1', label: '全部' },
            { key: '0', label: '待复制' },
            { key: '1', label: '复制中' },
            { key: '2', label: '复制成功' },
            { key: '6', label: '复制失败' },
          ]}
        />
        <Table
          dataSource={data}
          columns={columns}
          pagination={false}
          loading={loading}
          locale={{ emptyText: <Empty description="暂无数据" /> }}
          scroll={{ y: 480 }}
          rowKey="aliItemId"
        />
        <div style={{ marginTop: 8, textAlign: 'right' }}>
          <Pagination
            size="small"
            showSizeChanger
            pageSizeOptions={[20, 50, 100, 200]}
            current={pageNum}
            pageSize={pageSize}
            total={total}
            onChange={(p) => setPageNum(p)}
            onShowSizeChange={(_, s) => setPageSize(s)}
          />
        </div>
      </Card>
    </div>
  );
}


